package com.review.reviewsb.filter;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.review.reviewsb.domain.User;
import com.review.reviewsb.service.impl.UserServiceImpl;
import com.review.reviewsb.utils.JsonData;
import org.thymeleaf.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @program: reviewSb
 * @description: 登录拦截器
 * @author: YaoZhiLi
 * @create: 2021-07-04 15:54
 */
//@WebFilter(urlPatterns = "/api/v1/pri/*", filterName = "loginFilter")
public class LoginFilter implements Filter {
    private static final ObjectMapper ObjectMapper = new ObjectMapper();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String token = req.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            token = req.getParameter("token");
        }
        if (!StringUtils.isEmpty(token)) {
            //TODO 判断Token是否合法
            User user = UserServiceImpl.sessionMap.get(token);
            if (user != null) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                JsonData jsonData = JsonData.buildError("登录失败，token无效", -2);
                String s = ObjectMapper.writeValueAsString(jsonData);
                renderJson(resp, s);
            }
        } else {
            JsonData jsonData = JsonData.buildError("未登录", -3);
            String s = ObjectMapper.writeValueAsString(jsonData);
            renderJson(resp, s);
        }

    }

    private void renderJson(HttpServletResponse response, String json) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        try (PrintWriter writer = response.getWriter()) {
            writer.println(json);
        } catch (Exception e) {

        }
    }

    @Override
    public void destroy() {
        System.out.println("destroy");
    }
}